package ranks.types.mappings;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import ranks.types.Player;
import ranks.types.Position;
import ranks.types.Team;
import ranks.util.RankConstants;

public class ESPNPPRMapping extends PlayerMapping {
	
	public ESPNPPRMapping() {
		setUpVariables();
	}
	
	protected void setUpVariables() {
		this.dataURLs
			= new URL[]{ClassLoader.getSystemResource("espn-ffb-ppr.html")};
		this.startPhrase = "<table>";
		this.endPhrase = "</table>";
		this.parseCharacter = ",";
		this.removePhrases = new HashMap<String, String>();
		this.invalidPhrases = new ArrayList<String>();
		
		this.addToRemovePhrases();
		this.addToInvalidPhrases();
	}
	
	private void addToRemovePhrases() {
		this.removePhrases.put("\t", "");
		this.removePhrases.put("[<][^>]*[>]", ",");
		this.removePhrases.put("[,]+", ",");
		this.removePhrases.put(", ", ",");
		this.removePhrases.put("^,", "");
		this.removePhrases.put("&nbsp;", "0");
		this.removePhrases.put(",Rank,Player,Bye,Pos Rank,", "");
	}
	
	private void addToInvalidPhrases() {
		this.invalidPhrases.add(",");
	}
	
	protected boolean isDataValid(String data) {
		boolean valid = true;
		
		if(data == null || data.equals("")) {
			valid = false;
		}
		
		for(String invalid : this.invalidPhrases) {
			if(data.equals(invalid)) {
				valid = false;
			}
		}
		
		return valid;
	}
	
	protected Player createPlayer(String data) {
		Player player = null;

		String[] playerData = data.split(this.parseCharacter);
		
		Team team = Team.getTeam(playerData[3]);
		Position position = Position.getPosition(getPlayerPosition(playerData[5]));
		
		player = new Player(playerData[2], team, position);
		
		player.setRanking(RankConstants.ESPN_PPR_RANK, new Integer(playerData[1]));
		player.setRanking(RankConstants.ESPN_PPR_POS_RANK, getPositionRank(playerData[5]));
		
		return player;
	}
	
	private String getPlayerPosition(String data) {
		
		return data.replaceAll("[0-9]", "");
	}
	
	private Integer getPositionRank(String data) {
		
		String rankString = data.replaceAll("[a-zA-z]", "");
		
		return new Integer(rankString);
	}
}
